<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    
        <el-card>
          <el-form :inline="true" :model="searchVo" class="demo-form-inline">
            <el-form-item label="角色名称:">
              <el-input
                v-model="searchVo.fullName"
                placeholder="角色名称"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSubmit"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-circle-plus"
                @click="dialogFormVisible = true"
                >添加</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-folder" @click="exportRole()">导出</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="roles" border style="width: 100%" ref="multipleTable" id="out-table">
            <el-table-column type="selection" width="55px"> </el-table-column>
            <el-table-column fixed prop="roleId" label="ID" width="200px">
            </el-table-column>
            <el-table-column prop="name" label="角色名">
            </el-table-column>
            <el-table-column prop="description" label="角色描述">
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="65px">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"> </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="deleteClick(scope.row)"
                  type="text"
                  size="small"
                  >删除</el-button
                >
                <el-button
                  @click="openEditDialog(scope.row)"
                  type="text"
                  size="small"
                  >编辑</el-button
                >
                 <el-button
                  @click="fenPermission(scope.row)"
                  type="text"
                  size="small"
                  >分配权限</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentpage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-card>
        <el-dialog
          title="提示"
          :visible.sync="dialogFormVisible"
          width="60%"
          :before-close="handleClose"
        >
          <el-form label-width="100px" :model="role" :rules="rules" ref="roleForm">
            <el-form-item label="角色名称:" prop="name">
              <el-input v-model="role.name" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-form-item label="角色描述:" prop="description">
              <el-input
                placeholder="角色描述"
                auto-complete="off"
                v-model="role.description"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="排序号:" prop="sort">
              <el-input v-model="role.sort" placeholder="排序"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitDeptForm('roleForm')">提交</el-button>
              <el-button @click="resetDeptForm('roleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

         <el-dialog
            width="30%"
            title="权限菜单"
            :visible.sync="innerVisible"
            append-to-body>
                <el-tree
                    :data="tableData"
                    :check-strictly="true"
                    :props="defaultProps"
                    node-key="menuId"
                    ref="tree"
                    :default-expanded-keys="expandKeys"
                    :default-checked-keys="defaultCheckedKeys"
                    show-checkbox
                    @node-click="handleNodeClick">
                </el-tree>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="innerVisible = false">取 消</el-button>
                  <el-button type="primary" @click="addRolePermission()">确 定</el-button>
                </span>
            </el-dialog>
  </div>
</template>
<script>
import FileSaver from "file-saver"
import XLSX from "xlsx"
export default {
  data() {
    return {
      innerVisible:false,
      tableData:[],
      expandKeys:[],
      defaultCheckedKeys:[],
      isShowSelect: false, //控制树形结构是否显示
      dialogFormVisible: false, //控制弹出框显示和隐藏
      currentpage: 1, //标识当前页码
      pagesize: 5, //每页显示的条数
      total: 0, //总条数
      rolesTree: [], //存储部门的树形结构
      extendNode: [], //默认展开的树形节点
      roles: [], //查询所有部门的信息
      defaultProps: {
        children: "children",
        label: "name",
      },
      searchVo: {},
      role: {},
      roleId:0,
      rules: {
        simpleName: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
        ],
        
        fullName: [
          { required: true, message: "请输入部门全称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.onSubmit();
  },
  methods: {
    //获取选中得行
    async exportRole(){
       var selectionItems=this.$refs.multipleTable.selection;
       //let result= await this.$http.post("/system/role/download",selectionItems);
       // 为el-table添加一个id：out-table
    // 当el-table使用了fixed时会导出两次数据，所以要先进行判断
    var fix = document.querySelector('.el-table__fixed');
    var wb;
    if (fix) {
       // 如果有fixed，先移除，然后再添加上
       wb = XLSX.utils.table_to_book(document.querySelector("#out-table").removeChild(fix))
       document.querySelector("#out-table").appendChild(fix)
    }else{
       wb = XLSX.utils.table_to_book(document.querySelector("#out-table"))
    }
    var wbout = XLSX.write(wb, {
       bookType: "xlsx",
       bookSST: true,
       type: "array"
    });
    try {
       FileSaver.saveAs(
       　　new Blob([wbout], {
               type: "application/octet-stream"
          }),
          // 导出的文件名称
          "Data.xlsx"
       )
    } catch (e) {
       if (typeof console !== "undefined") console.log(e, wbout);
    }
    return wbout;
       
    },
    //添加角色权限
    async addRolePermission(){
         let checkPermissionIds=this.$refs.tree.getCheckedKeys();
         console.log(checkPermissionIds);
         let result= await this.$http.post("/system/role/addRolePermission/"+this.roleId,checkPermissionIds);
         if(result.data.code===20000){
              this.$message.success(result.data.message);
              this.innerVisible=false;
         }
    },
    //分配权限
    fenPermission(row){
        this.roleId=row.roleId;
        this.initMenu(row.roleId);
    },
    async initMenu(id) {
      let result = await this.$http.post(
        "/system/menu/fenPermission/"+id,
        this.searchVo
      );
      if (result.data.code === 20000) {
        this.tableData = result.data.data.allMenuTree;
        this.defaultCheckedKeys=result.data.data.checkedKey;
        this.expandKeys=result.data.data.checkedKey;
        this.innerVisible=true;
      }
    },

    //每页大小发生改变时触发
    handleSizeChange(val) {
      this.pagesize = val;
      this.onSubmit();
    },
    handleCurrentChange(val) {
      this.currentpage = val;
      this.onSubmit();
    },
    //删除市场部
     deleteClick(row) {
      this.$confirm("是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await this.$http.delete(
            "/system/role/deleteRole/" + row.roleId
          );
          if ((result.data.code = 20000)) {
            this.$message.success(result.data.message);
          }
          this.onSubmit();
        })
        .catch(() => {
          //几点取消的提示
        });
    },
    async openEditDialog(row){
         let result=await this.$http.get("/system/role/findById/"+row.roleId);
         if(result.data.code===20000){
             this.dialogFormVisible=true;
             this.role=result.data.data.role;
         }
    },
    //关闭弹出框
    handleClose(done) {
      this.role = {};
      this.dialogFormVisible = false;
    },
    submitDeptForm(roleForm){
        if(this.role.roleId){
            this.updateDeptForm(roleForm);
        }else{
           this.addDeptForm(roleForm);
        }
    },
    //添加部门
   async addDeptForm(roleForm) {
      //  this.$refs[roleForm].validate(async valid => {
      //       if (valid) {
                let result = await this.$http.post("/system/role/addRole", this.role);
                if ((result.data.code === 20000)) {
                  this.$message.success(result.data.message);
                }
                this.dialogFormVisible = false;
                this.onSubmit();
            // }else{
            //     return false;
            // }   
      //  })
    },
     //修改部门
   async updateDeptForm(roleForm) {
        
      //  this.$refs[roleForm].validate(async valid => {
      //       if (valid) {
                let result = await this.$http.post("/system/role/updateRole", this.role);
                if ((result.data.code === 20000)) {
                  this.$message.success(result.data.message);
                }
                this.dialogFormVisible = false;
                this.onSubmit();
            // }else{
            //     return false;
            // }   
      //  })
    },
    //搜索查询
    async onSubmit() {
      let result = await this.$http.post(
        "/system/role/searchRole/" + this.currentpage + "/" + this.pagesize,
        this.searchVo
      );
      if (result.data.code === 20000) {
        this.roles = result.data.data.records;
        
        this.total = parseInt(result.data.data.total);
      }
    },
    //初始化部门树形结构
    async initRole() {
      let result = await this.$http.get("/system/role/findDeptTree");
      if (result.data.code === 20000) {
        this.rolesTree = result.data.data.roleTree;
        console.log(this.rolesTree);
      }
    },
    stateFormatter(row, column, cellValue, index) {
      //显示员工状态是否在职
      return cellValue == "1" ? "展开" : "未展开";
    },
    handleNodeClick(data) {
      this.searchVo.roleId = data.roleId;
      this.onSubmit();
    },
    selectClassfy(data) {
      this.role.pname = data.fullName;
      this.role.pid = data.roleId;
      this.isShowSelect = false;
    },
    changeSelectTree() {
      this.isShowSelect = true;
    },
    hideParentClick(e) {
      var isOther =
        e.relatedTarget == null ||
        e.relatedTarget.closest("div.el-tree") == null ||
        e.relatedTarget.closest("div.el-tree").id != "floatTree";

      if (isOther) {
        this.isShowSelect = false;
      } else {
        e.target.focus();
      }
    },
    // 选择器的树节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>
<style scoped>
.el-main .el-container .el-aside {
  margin-top: 20px;
  height: 100%;
}
/*下拉框选择树*/
.objectTree {
  position: absolute;
  overflow: auto;
  z-index: 100;
  height: 200px;
  border: 1px solid #ddd;
  line-height: normal;
  z-index: 204;
}
.width-220 {
  width: 220px;
}
</style>